package com.wz.wiki.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wz.wiki.entity.pojo.Content;
import com.wz.wiki.entity.pojo.Doc;
import com.wz.wiki.entity.pojo.DocExample;
import com.wz.wiki.entity.req.DocQueryReq;
import com.wz.wiki.entity.req.DocSaveReq;
import com.wz.wiki.entity.resp.DocQueryResp;
import com.wz.wiki.entity.resp.PageResp;
import com.wz.wiki.exception.BusinessException;
import com.wz.wiki.exception.BusinessExceptionCode;
import com.wz.wiki.mapper.ContentMapper;
import com.wz.wiki.mapper.DocMapper;
import com.wz.wiki.service.DocService;
import com.wz.wiki.utils.CopyBeanUtils;
import com.wz.wiki.utils.RedisUtil;
import com.wz.wiki.utils.RequestContext;
import com.wz.wiki.utils.SnowFlake;
import com.wz.wiki.websocket.WebSocketServer;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.MDC;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName TestService.java
 * @create 2023年06月28日 下午2:53
 * @Description 电子书业务层接口实现类
 * @Version V1.0
 */
@Service
public class DocServiceImpl implements DocService {

    @Resource
    private DocMapper docMapper;

    @Resource
    private ContentMapper contentMapper;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private WebSocketService webSocketService;

    // RocketMQ
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public PageResp<DocQueryResp> selectList(DocQueryReq req) {
        DocExample docExample = new DocExample();
        // 创建查询条件
        DocExample.Criteria criteria = docExample.createCriteria();
        docExample.setOrderByClause("sort asc");

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Doc> docs = docMapper.selectByExample(docExample);

        PageInfo<Doc> docPageInfo = new PageInfo<>(docs);
        System.out.println("总行数：" + docPageInfo.getTotal());

        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(docPageInfo.getTotal());
        pageResp.setList(CopyBeanUtils.copyList(docs, DocQueryResp.class));

        return pageResp;
    }

    @Override
    public List<DocQueryResp> selectAll(DocQueryReq req) {
        DocExample docExample = new DocExample();

        // 创建查询条件
        DocExample.Criteria criteria = docExample.createCriteria();

        criteria.andEbookIdEqualTo(req.getEbookId());
        docExample.setOrderByClause("sort asc");

        List<Doc> docs = docMapper.selectByExample(docExample);

        return CopyBeanUtils.copyList(docs, DocQueryResp.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DocSaveReq req) {

        Long id = req.getId();
        Doc doc = CopyBeanUtils.copy(req, Doc.class);
        Content content = CopyBeanUtils.copy(req, Content.class);
        if (id == null) {
            // 新增
            id = snowFlake.nextId();
            doc.setId(id);
            doc.setViewCount(0);
            doc.setVoitCount(0);
            docMapper.insert(doc);

            content.setId(id);
            contentMapper.insert(content);
        }else {
            // 更新
            docMapper.updateByPrimaryKey(doc);
            int result = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (result==0){
                contentMapper.insert(content);
            }
        }
    }

    @Override
    public void delete(Long idsStr) {

        docMapper.deleteByPrimaryKey(idsStr);
    }

    @Override
    public void delete(String idsStr) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        List<Long> ids = Arrays.asList(idsStr.split(",")).stream()
                .map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        criteria.andIdIn(ids);

        docMapper.deleteByExample(docExample);
    }

    @Override
    public String findContent(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);
        // 增加阅读数+1
        docMapper.increaseViewCount(id);
        if (ObjectUtils.isEmpty(content)){
            return "";
        }
        return content.getContent();
    }

    @Override
    public void voit(Long id) {
        String remoteAddr = RequestContext.getRemoteAddr();
        String key = "doc_voit_" + id + "_" + remoteAddr;
        if (!redisUtil.validateRepeat(key, 3600*24)){
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }
        docMapper.increaseVoitCount(id);

        // 通知前端页面刷新点赞数
        String message = "【" + docMapper.selectByPrimaryKey(id).getName() + "】被点赞了".toString();
        String log_id = MDC.get("LOG_ID");
        // 异步发送消息
        webSocketService.sendWebSocketMsg(message,log_id);

        // MQ发送消息
//        rocketMQTemplate.convertAndSend("VOTE_TOPIC",message);
    }


    @Override
    public void updateEbookInfo() {
        docMapper.updateEbookInfo();
    }
}
